#!/bin/bash

#==========================
# FileName: rosmake.sh
# Author: Jetaime
# Email: mrpanwei1111@hotmail.com
# Source: https://gitee.com/mrpanwei/rads.git
# CreateTime: 2024-12-05
# Description: through this script compilation, you can intervene in the automatic version upgrade
#==========================================

if [ "$#" -eq 1 ]; then
    action=$1
    increment=1
    echo "Using action: $action with default increment: $increment"
elif [ "$#" -eq 2 ]; then
    action=$1
    increment=$2
    echo "Using action: $action with increment: $increment"
else
    action=patch
    increment=1
    echo "Using action: patch with default increment: $increment"
fi

pname=rads

echo "1.updating the version number"
bash ./src/${pname}/etc/otaauto.sh ${action} ${increment}

echo "2.start compiling"
catkin_make

if [ $? -ne 0 ]; then
    echo "Error: catkin_make failed."
    exit 1
else
	echo "3.start installing"
	catkin_make install
fi

echo "4.start compresse file"
cur_time=$(date +"%Y%m%d%H%M%S")
upd_file="upd${cur_time}.tar"
cd install && tar -cvf ${upd_file} include/rads etc/rads/usage.sh lib/rads share/rads/launch share/rads/msg share/rads/package.xml
cur_version=$(xmlstarlet sel -t -v "//version" "./share/${pname}/package.xml" 2>/dev/null)
filesize_bytes=$(stat -c%s "${upd_file}")
filesize_kb=$(echo "$filesize_bytes / 1024" | bc)
echo "upload file size in $filesize_kb kb."

echo "5.uploading the compressed package"

node_name=rads_
process_name=${pname}
publish_date=${cur_time}
publish_type=0
package_size=${filesize_kb}
is_must=1
major_minor_patch=${cur_version}
md5_code="nyd"
temp_down_path="test"
description="default modify"
ext="test"
ext2=-1

response=$(curl -X 'POST' 'http://apiautopilot.niyouduo.com/business/PadCommand/PostUploadOtaFile' \
  -H 'accept: */*' \
  -H 'Content-Type: multipart/form-data' \
  -F "ext=${ext}"\
  -F "node_name=${node_name}"\
  -F "publish_type=${publish_type}"\
  -F "md5_code=${md5_code}"\
  -F "ext2=${ext2}"\
  -F "temp_down_path=${temp_down_path}"\
  -F "major_minor_patch=${major_minor_patch}"\
  -F "package_size=${filesize_kb}"\
  -F "process_name=${process_name}"\
  -F "File=@${upd_file};type=application/x-tar"\
  -F "description=${description}"\
  -F "publish_date=${publish_date}"\
  -F "is_must=${is_must}")

responseval=$(echo "$response" | jq -r '.code')

if [ "$responseval" -eq 200 ]; then
  rm ${upd_file}
  echo ">>> congratulations,this upgrade has been completed.[veriosn is ${major_minor_patch}(${filesize_kb}kb)]"
else
  echo "network error"
fi
